package team.scau.laboratory_repair.service;

import com.querydsl.core.QueryResults;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.scau.laboratory_repair.common.base.BaseService;
import team.scau.laboratory_repair.common.page.MyPage;
import team.scau.laboratory_repair.modules.po.QRecordPhoto;
import team.scau.laboratory_repair.modules.po.RecordPhoto;
import team.scau.laboratory_repair.modules.repository.RecordPhotoRepository;
import team.scau.laboratory_repair.modules.repository.RecordRepository;

import java.util.List;

/**
 * @Author: 30254
 * @Date 18-10-22
 */
@Service
public class RecordPhotoService extends BaseService<RecordPhoto, RecordPhotoRepository> {

    @Autowired
    RecordPhotoRepository recordPhotoRepository;

    private QRecordPhoto qRecordPhoto = QRecordPhoto.recordPhoto;

    @Override
    public RecordPhotoRepository getRepository() {
        return recordPhotoRepository;
    }

    @Override
    public EntityPathBase<RecordPhoto> getQBase() {
        return qRecordPhoto;
    }

    public QueryResults<RecordPhoto> listOrByExample(MyPage page, RecordPhoto recordPhoto) {
        JPAQuery<RecordPhoto> jpaQuery = queryFactory.select(qRecordPhoto).from(qRecordPhoto);
        if (recordPhoto != null) {
            if (recordPhoto.getRecordId() != null) {
                jpaQuery = jpaQuery.where(qRecordPhoto.recordId.eq(recordPhoto.getRecordId()));
            }
        }
        jpaQuery = jpaQuery.where(qRecordPhoto.valid.eq(true));
        if (page != null) {
            jpaQuery = jpaQuery.orderBy(page.getSort()).offset(page.getPage()).limit(page.getSize());
        }
        return jpaQuery.fetchResults();
    }

    public List<RecordPhoto> listByRecordId(Long recordId) {
        JPAQuery<RecordPhoto> jpaQuery = queryFactory.select(qRecordPhoto).from(qRecordPhoto);
        if (recordId != null) {
            jpaQuery = jpaQuery.where(qRecordPhoto.recordId.eq(recordId));
        }
        jpaQuery = jpaQuery.where(qRecordPhoto.valid.eq(true));
        return jpaQuery.fetch();
    }

    public List<RecordPhoto> listByNoteId(Long noteId) {
        JPAQuery<RecordPhoto> jpaQuery = queryFactory.select(qRecordPhoto).from(qRecordPhoto);
        if (noteId != null) {
            jpaQuery = jpaQuery.where(qRecordPhoto.noteId.eq(noteId));
        }
        jpaQuery = jpaQuery.where(qRecordPhoto.valid.eq(true));
        return jpaQuery.fetch();
    }
}
